package com.whsr.readservice.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whsr.readservice.dao.DownBookMaintainMapper;
import com.whsr.readservice.dao.JobBatchMapper;
import com.whsr.readservice.dto.JobBatchRequest;
import com.whsr.readservice.enums.DownBookEnum;
import com.whsr.readservice.util.InterfaceUtil;
import com.whsr.readservice.vo.DownBookMaintain;
import com.whsr.readservice.vo.JobBatch;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Service
public class DownBookMaintainService {

    @Autowired
    private DownBookMaintainMapper downBookMaintainMapper;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private ChapterService chapterService;

    @Autowired
    private ChapterContentService chapterContentService;

    @Autowired
    private JobBatchMapper jobBatchMapper;

    public List<Integer> getBookIdsBystatus(Integer status){
        return downBookMaintainMapper.selectBookIdsByStatus(status);
    }

    public int insertDownBookMaintains(List<DownBookMaintain> downBookMaintains) {
        return downBookMaintainMapper.insertDownBookMaintains(downBookMaintains);
    }

    public int updateDownBookMaintains(List<Integer> bookIds, Integer status){
        return downBookMaintainMapper.updateDownBookMaintains(bookIds, status);
    }

    public void downBookJob(Integer jobType){
        if(this.isNoComplateBookIdList()){

        } else {
            JobBatch jobBatch = new JobBatch();
            jobBatch.setCreateTime(new Date());
            jobBatch.setJobType(jobType);
            try{
                articleService.insertArticles(jobBatch);
            } catch (Exception e) {
                e.printStackTrace();
            }
            try{
                chapterService.insertChapters(jobBatch);
            } catch (Exception e) {
                e.printStackTrace();
            }
            try{
                chapterContentService.inserChapterContents(jobBatch);
            } catch (Exception e) {
                e.printStackTrace();
            }
            jobBatchMapper.insertJobBatch(jobBatch);
        }
    }

    public PageInfo<JobBatchRequest> getJobList(Integer pageNo, Integer pageSize, JobBatchRequest jobBatchRequest) {
        PageHelper.startPage(pageNo, pageSize);
        List<JobBatchRequest> list = jobBatchMapper.selectJobList(jobBatchRequest);
        PageInfo<JobBatchRequest> pageInfo = new PageInfo<JobBatchRequest>(list);
        return pageInfo;
    }

    public boolean isNoComplateBookIdList(){
        List<Integer> bookIds = downBookMaintainMapper.selectBookIdsByNoStatus(3);
        if(bookIds.size() > 0){
            return false;
        }
        return true;
    }

    public boolean isExistsByBookId(Integer bookId){
        Integer count = downBookMaintainMapper.selectCountByBookId(bookId);
        if(count > 0){
            return true;
        }
        return false;
    }

    public Map<String, Object> importBookIds(String fileName, MultipartFile file) throws IOException {
        Map<String, Object> msg = new HashMap();
        List<DownBookMaintain> downBookMaintains = new ArrayList<>();
        List<Integer> existBookIds = new ArrayList<>();
        List<String> errorBookIds = new ArrayList<>();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            msg.put("msg", "上传文件格式不正确");
            return msg;
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        if(sheet != null){
            for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                Row row = sheet.getRow(r);
                if (row == null){
                    continue;
                }
                //将单元格设置成文本类型
                row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                String bookIdStr = row.getCell(0).getStringCellValue();
                //单元格空，则录入哪一行为空
                if(bookIdStr == null || bookIdStr.trim().isEmpty()){
                    String errorStr = "第"+(r+1)+"为空";
                    errorBookIds.add(errorStr);
                    continue;
                }
                //将String 转换成 int 错误则录入错误信息
                Integer bookId = null;
                try {
                    bookId = Integer.valueOf(bookIdStr);
                } catch (NumberFormatException e) {
                    errorBookIds.add("第"+(r+1)+"行为错误书号：" + bookIdStr);
                    continue;
                }
                //如果该书号存在作品信息，不导入
                if(this.isExistsByBookId(bookId)){
                    existBookIds.add(bookId);
                    continue;
                }
                DownBookMaintain downBookMaintain = new DownBookMaintain();
                downBookMaintain.setBookId(bookId);
                downBookMaintain.setStatus(DownBookEnum.WAIT_ARTICLE.getCode());
                if(downBookMaintains.contains(downBookMaintain)){
                    errorBookIds.add("第"+(r+1)+"行为重复书号：" + bookIdStr);
                } else {
                    downBookMaintains.add(downBookMaintain);
                }

            }
            if(downBookMaintains.size() > 0){
                int forNum = (downBookMaintains.size() % InterfaceUtil.MAX_COUNT) > 0 ? (downBookMaintains.size() / InterfaceUtil.MAX_COUNT) + 1 : (downBookMaintains.size() / InterfaceUtil.MAX_COUNT);
                for (int i = 0; i < forNum; i++){
                    List<DownBookMaintain> newUpdatebookIds = null;
                    if(i != forNum -1){
                        newUpdatebookIds = downBookMaintains.subList(i*InterfaceUtil.MAX_COUNT, (i+1)*InterfaceUtil.MAX_COUNT);
                    } else {
                        newUpdatebookIds = downBookMaintains.subList(i*InterfaceUtil.MAX_COUNT, downBookMaintains.size());
                    }
                    if(newUpdatebookIds != null && newUpdatebookIds.size() > 0){
                        try{
                            //this.insertDownBookMaintains(newUpdatebookIds);
                        } catch (Exception e) {
                            continue;
                        }
                    }
                }
            }
        } else {
            msg.put("msg", "excel的Sheet第一页没有内容");
            return msg;
        }
        msg.put("msg", "success");
        msg.put("exist", existBookIds);
        msg.put("error", errorBookIds);
        return msg;
    }
}
